package leecode;

/**
 * 功能描述：矩阵中的路径
 *
 * @Author: lwg
 * @Date: 2021/4/7 0:50
 */
public class demo12 {

    public static boolean exist(char[][] board, String word) {
        char[] words=word.toCharArray();
        for(int i=0;i<board.length;i++){
            for(int j=0;j<board[0].length;j++){
                if(dfs(board,words,i,j,0)){  //调用是i,j可以依次遍历往下找
                    return true;
                }
            }
        }
        return false;
    }
    public static boolean dfs(char[][] board, char[] word, int i, int j, int k){
        if(i<0||i>=board.length||j<0||j>=board[0].length||board[i][j]!=word[k]){
            return false;
        }
        if(k==word.length-1) return true;  //因为k是从0开始的,所以word.length必须减1,否则将会超出索引
        board[i][j]='\0'; //防止走过的再走一遍(下上右左,此时找到了此位置的字符,当在下一个字符判断时,不用再次走一步)
        boolean res=dfs(board,word,i+1,j,k+1)||dfs(board,word,i-1,j,k+1)
                ||dfs(board,word,i,j+1,k+1)||dfs(board,word,i,j-1,k+1);
        board[i][j]=word[k]; //回溯时将寻找到的字符放入对应的位置中
        return res;
    }

    public static void main(String[] args) {
        char[][] board= {{'A','B','C','E'},
                         {'S','F','C','S'},
                         {'A','D','E','E'}};
        String word="ABCCED";
        System.out.println(exist(board, word));
    }
}
